<?php

namespace App\Db;

use App\Utils\Date;
use Illuminate\Support\Facades\DB;

class Columns
{
    public const TABLE = 'category';

    public function getColumns($exceptDel = false, $siteId = 0)
    {
        $data = DB::table(self::TABLE)->where(['is_del' => 0, 'site' => $siteId])->orderByDesc('create_time')->get()->toArray();

        $blogGroupData = DB::table(Blog::BLOG)->select(DB::raw('count(id) as c, category'))->where(['site' => $siteId]);
        if ($exceptDel) {
            $blogGroupData = $blogGroupData->where(['is_del' => 0]);
        }
        $blogGroupData = $blogGroupData->groupBy(['category'])->get()->toArray();
        $groupData = array_column($blogGroupData, null, 'category');
        array_walk($data, function($v) use($groupData) {
            $v->count = $groupData[$v->id]->c ?? 0;
        });
        return $data;
    }

    public function addColumn(string $columnName, $siteId)
    {
        return DB::table(self::TABLE)->insertGetId([
            'site' => $siteId,
            'name' => $columnName,
            'create_time' => Date::now(),
            'is_del' => 0
        ]);
    }

    public function saveColumn($data, $siteId)
    {
        return DB::table(self::TABLE)->where(['id' => $data['id']])->update([
            'name' => $data['name'],
            'site' => $siteId,
            'create_time' => Date::now(),
            'is_del' => 0
        ]);
    }

    public function deleteCategory($id)
    {
        return DB::table(self::TABLE)->where(['id' => $id])->update([
            'is_del' => 1,
            'update_time' => Date::now()
        ]);
    }
}
